<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref,nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: [],
      yAxisData: []
    })
  }
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartContainer.value) return
  
  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartContainer.value)
  updateChart()
}

const updateChart = () => {
  if (!chartInstance) return

  const option = {
    legend: {
      right: '50px',
      top: '30px',
      data: ['已提箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData || [])
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '已提箱量',
        data: Array.from(props.config.yAxisData || []),
        type: 'bar',
        label: {
              show: true, // 显示标签
              position: 'top',
              formatter: '{c}个', // 显示数据值
            }
        
      }
    ]
  }

  chartInstance.setOption(option)
}
// 监听窗口变化，重新调整图表大小
const handleResize = () => {
  chartInstance?.resize()
}

onMounted(() => {
  nextTick(() => { 
    initChart()
  })
 
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听配置变化
watch(() => props.config,() => {
      if (!chartInstance) {
        initChart()
      } else {
        updateChart()
      }
  },
  { deep: true}
)
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  // 可以添加必要的样式
  width: 100%;
}
</style>